package cn.harry.cabinet

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.InputType
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import cn.harry.cabinet.repository.ConfigurationRepository
import cn.harry.cabinet.theme.manager.ThemeManager
import cn.harry.cabinet.utils.AppConfigKeys
import cn.harry.cabinet.utils.ConnectivityLiveData
import cn.harry.cabinet.utils.VersionUtil
import cn.harry.cabinet.utils.logConfigChange
import cn.harry.cabinet.view.SystemConfigActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.security.MessageDigest
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class MainActivity : AppCompatActivity() {
    
    private lateinit var timeText: TextView
    private lateinit var versionText: TextView
    private lateinit var networkStatusText: TextView
    private lateinit var networkStatusIcon: ImageView
    private lateinit var titleText: TextView
    private lateinit var deviceNumberText: TextView
    private lateinit var handler: Handler
    private lateinit var timeRunnable: Runnable
    private lateinit var connectivityLiveData: ConnectivityLiveData
    private lateinit var configurationRepository: ConfigurationRepository
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        
        // 初始化视图（必须在applyTheme之前）
        initViews()
        
        // 应用保存的主题
        applyTheme()
        
        // 设置点击事件
        setupClickListeners()
        
        // 启动时间更新
        startTimeUpdate()

        // 应用首页配置
        applyHomeConfigs()
    }
    
    private fun initViews() {
        timeText = findViewById(R.id.tv_date_time)
        versionText = findViewById(R.id.tv_version)
        networkStatusText = findViewById(R.id.tv_network_status)
        networkStatusIcon = findViewById(R.id.iv_network_status)
        titleText = findViewById(R.id.tv_title)
        deviceNumberText = findViewById(R.id.tv_device_number)
        handler = Handler(Looper.getMainLooper())
        configurationRepository = ConfigurationRepository(application)

        // 动态设置版本号，避免手动更新字符串资源
        versionText.text = VersionUtil.getFormattedVersion(this)

        // 初始化网络状态并开始观察
        connectivityLiveData = ConnectivityLiveData(this)
        connectivityLiveData.observe(this) { isConnected ->
            updateNetworkStatus(isConnected == true)
        }
    }

    private fun updateNetworkStatus(isConnected: Boolean) {
        runOnUiThread {
            networkStatusText.text = if (isConnected) "已连接" else "未连接"
            networkStatusIcon.setImageResource(if (isConnected) R.drawable.ic_network_connected else R.drawable.ic_network)
        }
    }

    private fun applyHomeConfigs() {
        lifecycleScope.launch(Dispatchers.IO) {
            try {
                val configs = configurationRepository.getByType(AppConfigKeys.TYPE_HOME)
                val map = configs.associateBy { it.key }
                val title = map[AppConfigKeys.KEY_HOME_TITLE]?.value
                val labelReturn = map[AppConfigKeys.KEY_HOME_LABEL_RETURN]?.value
                val labelTake = map[AppConfigKeys.KEY_HOME_LABEL_TAKE]?.value
                val deviceNo = map[AppConfigKeys.KEY_HOME_DEVICE_NUMBER]?.value

                withContext(Dispatchers.Main) {
                    if (!title.isNullOrBlank()) {
                        titleText.text = title
                    }
                    if (!deviceNo.isNullOrBlank()) {
                        deviceNumberText.text = "设备编号: $deviceNo"
                    }
                    // 更新卡片上的文字
                    val returnLabelView = findViewById<TextView>(R.id.return_label_text)
                    val takeLabelView = findViewById<TextView>(R.id.take_label_text)
                    if (returnLabelView != null && !labelReturn.isNullOrBlank()) {
                        returnLabelView.text = labelReturn
                    }
                    if (takeLabelView != null && !labelTake.isNullOrBlank()) {
                        takeLabelView.text = labelTake
                    }
                }
            } catch (_: Exception) {
                // ignore
            }
        }
    }
    
    private fun setupClickListeners() {
        // 还仪器卡片 - 直接进入刷卡页面
        findViewById<CardView>(R.id.cv_return)?.setOnClickListener {
            val intent = Intent(this, cn.harry.cabinet.view.CardScanActivity::class.java)
            intent.putExtra(cn.harry.cabinet.view.BaseAuthActivity.EXTRA_ACTION_TYPE, 
                cn.harry.cabinet.view.BaseAuthActivity.ACTION_RETURN)
            startActivity(intent)
        }
        
        // 取仪器卡片 - 直接进入人脸识别页面
        findViewById<CardView>(R.id.cv_take)?.setOnClickListener {
            val intent = Intent(this, cn.harry.cabinet.view.FaceRecognitionActivity::class.java)
            intent.putExtra(cn.harry.cabinet.view.BaseAuthActivity.EXTRA_ACTION_TYPE, 
                cn.harry.cabinet.view.BaseAuthActivity.ACTION_TAKE)
            startActivity(intent)
        }
        
        // 设置按钮
        findViewById<View>(R.id.btn_settings)?.setOnClickListener {
            showPasswordDialog()
        }
    }
    
    private fun startTimeUpdate() {
        timeRunnable = object : Runnable {
            override fun run() {
                updateTime()
                handler.postDelayed(this, 30000) // 每30秒更新一次
            }
        }
        handler.post(timeRunnable)
    }
    
    private fun updateTime() {
        val dateFormat = SimpleDateFormat("EEEE yyyy-MM-dd HH:mm", Locale.CHINESE)
        val currentTime = dateFormat.format(Date())
        timeText.text = currentTime
    }
    
    /**
     * 显示密码验证对话框
     */
    private fun showPasswordDialog() {
        val passwordInput = EditText(this).apply {
            inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
            hint = "请输入管理员密码"
            setPadding(50, 40, 50, 40)
        }
        
        AlertDialog.Builder(this)
            .setTitle("验证密码")
            .setMessage("请输入管理员密码以进入系统配置")
            .setView(passwordInput)
            .setPositiveButton("确定") { dialog, _ ->
                val password = passwordInput.text.toString()
                if (password.isNotEmpty()) {
                    verifyPassword(password)
                } else {
                    Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show()
                }
                dialog.dismiss()
            }
            .setNegativeButton("取消") { dialog, _ ->
                dialog.dismiss()
            }
            .setCancelable(true)
            .show()
    }
    
    /**
     * 验证密码
     */
    private fun verifyPassword(password: String) {
        lifecycleScope.launch {
            try {
                val storedPassword = withContext(Dispatchers.IO) {
                    getConfigValue(AppConfigKeys.TYPE_SECURITY, AppConfigKeys.ADMIN_PASSWORD)
                }
                
                val passwordHash = hashPassword(password)
                val defaultPasswordHash = hashPassword("1234")
                
                // 如果没有设置密码，使用默认密码验证
                val expectedPassword = if (storedPassword.isNullOrEmpty()) {
                    defaultPasswordHash
                } else {
                    storedPassword
                }
                
                if (passwordHash == expectedPassword) {
                    // 密码正确，跳转到系统配置
                    logConfigChange(
                        scope = lifecycleScope,
                        subType = "SETTINGS_ACCESS",
                        description = "管理员密码验证成功，进入系统配置",
                        oldValue = "密码验证",
                        newValue = "已授权访问系统设置"
                    )
                    val intent = Intent(this@MainActivity, SystemConfigActivity::class.java)
                    startActivity(intent)
                } else {
                    // 密码错误
                    logConfigChange(
                        scope = lifecycleScope,
                        subType = "SETTINGS_ACCESS",
                        description = "管理员密码验证失败",
                        oldValue = "尝试访问",
                        newValue = "密码错误，拒绝访问"
                    )
                    Toast.makeText(this@MainActivity, "密码错误，请重试", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                Toast.makeText(this@MainActivity, "验证失败: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    /**
     * 获取配置值
     */
    private suspend fun getConfigValue(type: String, key: String): String? {
        val configRepository = ConfigurationRepository(application)
        val config = configRepository.getByTypeAndKey(type, key)
        return config?.value
    }
    
    /**
     * 密码哈希
     */
    private fun hashPassword(password: String): String {
        val bytes = MessageDigest.getInstance("SHA-256").digest(password.toByteArray())
        return bytes.joinToString("") { "%02x".format(it) }
    }
    
    override fun onDestroy() {
        super.onDestroy()
        // 停止时间更新
        handler.removeCallbacks(timeRunnable)
    }

    override fun onResume() {
        super.onResume()
        // 返回首页后刷新首页配置
        applyHomeConfigs()
        // 重新应用主题，以防在其他界面修改了主题
        applyTheme()
        
        // 监听主题变化
        observeThemeChanges()
    }
    
    /**
     * 监听主题变化
     */
    private fun observeThemeChanges() {
        // 注册SharedPreferences监听器
        val prefs = getSharedPreferences("theme_preferences", Context.MODE_PRIVATE)
        val currentThemeKey = prefs.getString("current_theme", "tech_blue")
        
        // 检查主题是否有变化
        lifecycleScope.launch {
            val currentTheme = ThemeManager.getCurrentTheme(this@MainActivity)
            applyHomepageTheme(currentTheme)
        }
    }
    
    /**
     * 应用保存的主题
     */
    private fun applyTheme() {
        lifecycleScope.launch {
            try {
                val theme = withContext(Dispatchers.IO) {
                    ThemeManager.loadThemeFromDatabase(this@MainActivity)
                }
                withContext(Dispatchers.Main) {
                    ThemeManager.applyTheme(this@MainActivity, theme)
                    // 应用首页特定的主题更新
                    applyHomepageTheme(theme)
                }
            } catch (e: Exception) {
                // 如果加载失败，使用默认主题
                val defaultTheme = ThemeManager.getCurrentTheme(this@MainActivity)
                ThemeManager.applyTheme(this@MainActivity, defaultTheme)
                applyHomepageTheme(defaultTheme)
            }
        }
    }
    
    /**
     * 应用首页特定的主题样式
     */
    private fun applyHomepageTheme(theme: ThemeManager.Theme) {
        // 确保视图已经初始化
        if (!::titleText.isInitialized || !::timeText.isInitialized || 
            !::deviceNumberText.isInitialized || !::networkStatusText.isInitialized || 
            !::networkStatusIcon.isInitialized) {
            android.util.Log.w("MainActivity", "Views not initialized yet, skipping theme application")
            return
        }
        
        val themeColors = ThemeManager.getThemeColors(theme)
        
        // 更新主背景 - 使用主题专属的渐变背景
        val backgroundDrawable = when (theme) {
            ThemeManager.Theme.CHINA_RED -> ContextCompat.getDrawable(this, R.drawable.china_red_background)
            ThemeManager.Theme.VIBRANT_ORANGE -> ContextCompat.getDrawable(this, R.drawable.vibrant_orange_background)
            ThemeManager.Theme.TECH_BLUE -> ContextCompat.getDrawable(this, R.drawable.tech_blue_background)
        }
        findViewById<View>(R.id.main)?.background = backgroundDrawable
        
        // 更新卡片背景
        findViewById<CardView>(R.id.cv_return)?.setCardBackgroundColor(ContextCompat.getColor(this, themeColors.primary))
        findViewById<CardView>(R.id.cv_take)?.setCardBackgroundColor(ContextCompat.getColor(this, themeColors.secondary))
        
        // 更新文字颜色
        val textColor = ContextCompat.getColor(this, themeColors.onSurface)
        val accentColor = ContextCompat.getColor(this, themeColors.accent)
        
        titleText.setTextColor(textColor)
        timeText.setTextColor(textColor)
        deviceNumberText.setTextColor(textColor)
        networkStatusText.setTextColor(textColor)
        
        // 更新图标颜色
        networkStatusIcon.setColorFilter(accentColor)
        
        // 更新设置按钮样式
        findViewById<View>(R.id.btn_settings)?.apply {
            background?.setTint(ContextCompat.getColor(this@MainActivity, themeColors.surfaceVariant))
        }
        
        android.util.Log.d("MainActivity", "Applied homepage theme: ${theme.displayName}")
    }
    
    /**
     * 公开方法：供外部调用以更新主题
     * 当从系统配置页面返回时，可以调用此方法立即更新主题
     */
    fun updateTheme() {
        applyTheme()
    }
    
    /**
     * 获取当前主题状态（用于调试）
     */
    fun getCurrentThemeInfo(): String {
        val theme = ThemeManager.getCurrentTheme(this)
        return "当前主题: ${theme.displayName} (${theme.key})"
    }
}